package com.aimusic.config;

import com.aimusic.Handler.ChatWebSocketHandler;
import com.aimusic.interceptor.ChatHandshakeInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;

// 仅保留配置注解，通过构造函数注入依赖
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    private final ChatWebSocketHandler chatWebSocketHandler;
    private final ChatHandshakeInterceptor chatHandshakeInterceptor;

    // 构造函数注入（Spring会自动寻找对应的Bean）
    public WebSocketConfig(ChatWebSocketHandler chatWebSocketHandler,
                           ChatHandshakeInterceptor chatHandshakeInterceptor) {
        this.chatWebSocketHandler = chatWebSocketHandler;
        this.chatHandshakeInterceptor = chatHandshakeInterceptor;
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // 注册WebSocket端点，支持前端连接
        registry.addHandler(chatWebSocketHandler, "/api/ws/chat")
                .addInterceptors(chatHandshakeInterceptor)
                .setAllowedOrigins("*"); // 生产环境需替换为具体域名
    }

    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        // 1. 连接超时：30 分钟（单位：毫秒，避免频繁超时）
        container.setMaxSessionIdleTimeout(1800000L);
        // 2. 其他可选配置（避免消息过大导致断开）
        container.setMaxTextMessageBufferSize(8192); // 文本消息缓冲区大小
        container.setMaxBinaryMessageBufferSize(8192); // 二进制消息缓冲区大小
        return container;
    }
}
    